<template>
  <div class="order-list-container">
    <div class="header">
      <h1>{{ pageTitle || '订单管理' }}</h1>
      <p v-if="pageSubtitle" class="header-subtitle">{{ pageSubtitle }}</p>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索订单号、客户邮箱..."
        clearable
        style="width: 300px"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select v-model="statusFilter" placeholder="订单状态" clearable @change="handleSearch" style="width: 180px">
        <el-option label="全部状态" value="" />
        <el-option label="待处理" value="processing" />
        <el-option label="已发货" value="shipped" />
        <el-option label="已完成" value="completed" />
        <el-option label="已取消" value="cancelled" />
      </el-select>

      <el-button @click="handleSearch" type="primary">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 订单列表 -->
    <el-table :data="orders" v-loading="loading" stripe>
      <el-table-column prop="order_number" label="订单号" width="200" fixed />
      <el-table-column prop="user_email" label="客户邮箱" width="200" />
      <el-table-column prop="shipping_full_name" label="收货人" width="150" />
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status_display }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="total_price" label="订单金额" width="120">
        <template #default="{ row }">
          €{{ row.total_price }}
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="viewDetail(row)">查看详情</el-button>
          <el-button link type="primary" @click="showStatusDialog(row)">更新状态</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="900px">
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.order_number }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentOrder.status)">{{ currentOrder.status_display }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户">{{ currentOrder.user_name }} ({{ currentOrder.user_email }})</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(currentOrder.created_at) }}</el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 24px">收货地址</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="收货人">{{ currentOrder.shipping_full_name }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{ currentOrder.shipping_phone }}</el-descriptions-item>
          <el-descriptions-item label="地址" :span="2">
            {{ currentOrder.shipping_address_line1 }}
            {{ currentOrder.shipping_address_line2 ? ', ' + currentOrder.shipping_address_line2 : '' }},
            {{ currentOrder.shipping_city }}, {{ currentOrder.shipping_state }} {{ currentOrder.shipping_postal_code }},
            {{ currentOrder.shipping_country }}
          </el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 24px">订单商品</h3>
        <el-table :data="currentOrder.items" border>
          <el-table-column prop="product_name" label="商品" />
          <el-table-column prop="variant_name" label="规格" />
          <el-table-column prop="unit_price" label="单价">
            <template #default="{ row }">€{{ row.unit_price }}</template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" />
          <el-table-column prop="subtotal" label="小计">
            <template #default="{ row }">€{{ row.subtotal }}</template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 16px; text-align: right">
          <div><strong>商品小计：</strong> €{{ currentOrder.subtotal_price }}</div>
          <div><strong>运费：</strong> €{{ currentOrder.shipping_cost }}</div>
          <div style="font-size: 18px; color: #e74c3c; margin-top: 8px">
            <strong>订单总计：</strong> €{{ currentOrder.total_price }}
          </div>
        </div>

        <div v-if="currentOrder.note" style="margin-top: 16px">
          <h4>客户备注</h4>
          <p>{{ currentOrder.note }}</p>
        </div>

        <div v-if="currentOrder.admin_note" style="margin-top: 16px">
          <h4>管理员备注</h4>
          <p>{{ currentOrder.admin_note }}</p>
        </div>

        <div v-if="currentOrder.tracking_number" style="margin-top: 16px">
          <h4>物流单号</h4>
          <p>{{ currentOrder.tracking_number }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="showStatusDialog(currentOrder)">更新状态</el-button>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog v-model="statusDialogVisible" title="更新订单状态" width="500px">
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="订单状态">
          <el-select v-model="statusForm.status" style="width: 100%">
            <el-option label="待处理" value="processing" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态备注">
          <el-input v-model="statusForm.note" type="textarea" :rows="3" placeholder="状态变更备注..." />
        </el-form-item>
        <el-form-item label="物流单号">
          <el-input v-model="statusForm.tracking_number" placeholder="如已发货，请输入物流单号" />
        </el-form-item>
        <el-form-item label="管理员备注">
          <el-input v-model="statusForm.admin_note" type="textarea" :rows="3" placeholder="内部备注..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateStatus">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getOrderList, getOrderDetail, updateOrderStatus, updateAdminNote, type Order } from '@/api/order'
import { usePageMeta } from '@/composables/usePageMeta'

const { pageTitle, pageSubtitle } = usePageMeta()

const loading = ref(false)
const orders = ref<Order[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const searchQuery = ref('')
const statusFilter = ref('')

const detailDialogVisible = ref(false)
const statusDialogVisible = ref(false)
const currentOrder = ref<Order | null>(null)
const statusForm = ref({
  status: '',
  note: '',
  tracking_number: '',
  admin_note: ''
})

const getStatusType = (status: string) => {
  const typeMap: Record<string, any> = {
    processing: 'warning',
    shipped: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return typeMap[status] || 'info'
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const fetchOrders = async () => {
  loading.value = true
  try {
    const res = await getOrderList({
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchQuery.value,
      status: statusFilter.value,
      ordering: '-created_at'
    })
    orders.value = res?.results ?? []
    total.value = res?.count ?? 0
  } catch (error: any) {
    ElMessage.error(error.message || '获取订单列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

const handleReset = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  currentPage.value = 1
  fetchOrders()
}

const handlePageChange = () => {
  fetchOrders()
}

const handleSizeChange = () => {
  currentPage.value = 1
  fetchOrders()
}

const viewDetail = async (order: Order) => {
  try {
    const res = await getOrderDetail(order.id)
    currentOrder.value = res
    detailDialogVisible.value = true
  } catch (error: any) {
    ElMessage.error(error.message || '获取订单详情失败')
  }
}

const showStatusDialog = (order: Order) => {
  currentOrder.value = order
  statusForm.value = {
    status: order.status,
    note: '',
    tracking_number: order.tracking_number || '',
    admin_note: order.admin_note || ''
  }
  statusDialogVisible.value = true
  detailDialogVisible.value = false
}

const handleUpdateStatus = async () => {
  if (!currentOrder.value) return

  try {
    // 更新状态
    await updateOrderStatus(currentOrder.value.id, {
      status: statusForm.value.status,
      note: statusForm.value.note
    })

    // 更新备注和物流单号
    if (statusForm.value.admin_note || statusForm.value.tracking_number) {
      await updateAdminNote(currentOrder.value.id, {
        admin_note: statusForm.value.admin_note,
        tracking_number: statusForm.value.tracking_number
      })
    }

    ElMessage.success('订单状态更新成功')
    statusDialogVisible.value = false
    fetchOrders()
  } catch (error: any) {
    // 错误已经在响应拦截器中处理并显示，这里不需要再次显示
    // 只需要记录日志即可
    console.error('更新订单状态失败:', error)
  }
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.order-list-container {
  padding: 24px;
}

.header {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 24px;
}

.header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.header-subtitle {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.filter-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  align-items: center;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.order-detail h3 {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
}

.order-detail h4 {
  font-size: 14px;
  font-weight: 600;
  color: #34495e;
  margin-bottom: 8px;
}
</style>
